package zhr.os;

import java.util.Stack;

public class test1 {
        public  static  int solution(String solutions) {
            Stack<Integer> nums = new Stack<>();
            Stack<Character> ops = new Stack<>();
            int num = 0;
            int n = solutions.length();
            for (int i = 0; i < n; i++) {
                char c = solutions.charAt(i);
                if (Character.isDigit(c)) {
                    num = num * 10 + (c - '0');
                    if (i + 1 == n || !Character.isDigit(solutions.charAt(i + 1))) {
                        nums.push(num);
                        num = 0;
                    }
                } else if (c == '(') {
                    ops.push(c);
                } else if (c == ')') {
                    while (!ops.isEmpty() && ops.peek() != '(') {
                        nums.push(applyOp(ops.pop(), nums.pop(), nums.pop()));
                    }
                    ops.pop();
                } else if (c == '+' || c == '-' || c == '*' || c == '/') {
                    while (!ops.isEmpty() && precedence(c) <= precedence(ops.peek())) {
                        nums.push(applyOp(ops.pop(), nums.pop(), nums.pop()));
                    }
                    ops.push(c);
                }
            }
            while (!ops.isEmpty()) {
                nums.push(applyOp(ops.pop(), nums.pop(), nums.pop()));
            }
            return nums.pop();
        }

        private  static int applyOp(char op, int b, int a) {
            switch (op) {
                case '+': return a + b;
                case '-': return a - b;
                case '*': return a * b;
                case '/':
                    if (b == 0) throw new UnsupportedOperationException("Cannot divide by zero");
                    return a / b;
                default: throw new UnsupportedOperationException("Unsupported operation: " + op);
            }
        }

        private static int precedence(char op) {
            if (op == '+' || op == '-') return 1;
            if (op == '*' || op == '/') return 2;
            return 0;
        }


    public static void main(String[] args) {
        // 你可以添加更多测试用例
        System.out.println(solution("1+1") == 2);
        System.out.println(solution("3+4*5/(3+2)") == 7);
        System.out.println(solution("4+2*5-2/1") == 12);
        System.out.println(solution("(1+(4+5+2)-3)+(6+8)") == 23);
    }
}